﻿using System;
using System.Linq;
using Altairis.FluffyCloud.Data.Views;

namespace Altairis.FluffyCloud.WebCore.Pages.Forum {

    public partial class HomePage : DbPage {

        public IQueryable<TopicCategoryInfo> CategoryList_GetData() {
            var q = from c in this.DbContext.TopicCategories
                    orderby c.SortOrder descending, c.Name
                    select new TopicCategoryInfo {
                        TopicCategoryId = c.TopicCategoryId,
                        Name = c.Name,
                        Topics = from t in c.Topics
                                 select new TopicInfo {
                                     TopicId = t.TopicId,
                                     Name = t.Name,
                                     UserName = t.UserName,
                                     DateCreated = t.DateCreated,
                                     Description = t.Description,
                                     LastPostDate = t.Posts.Any() ? t.Posts.OrderByDescending(p => p.DateCreated).FirstOrDefault().DateCreated : DateTimeOffset.MaxValue,
                                     LastPostUserName = t.Posts.Any() ? t.Posts.OrderByDescending(p => p.DateCreated).FirstOrDefault().UserName : null,
                                     LastVisitDate = t.UserStates.Any(s => s.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)) ? t.UserStates.FirstOrDefault(s => s.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)).LastVisitDate : DateTimeOffset.MaxValue,
                                     PostCount = t.Posts.Count()
                                 }
                    };
            return q;
        }

        protected void ButtonNewTopic_Click(object sender, EventArgs e) {
            this.Response.RedirectToRoute("ForumCreate");
        }
    }
}